package softtech.app.secretcaller;

import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

public class ControlUploadToServer extends AsyncTask<Void, Void, Void> {
	
	final String TAG = "CONTROL SYNC WITH SERVER";

	Context context;
	
	DatabaseHandler db;
	
	int user_id;
	
	String result_from_server;
	
	DatabaseContact mContact;
	
	public ControlUploadToServer(Context context , DatabaseContact contact ){
		super();
		this.context = context;
		db = new DatabaseHandler(context);
		result_from_server = "";
		mContact = contact;
		user_id = checkLogin();
		//Log.e(TAG , mContact.toListNameValuePair().toString());
	}
	
	@Override
	protected Void doInBackground(Void... params) {
		HttpRequest request = new HttpRequest();
		result_from_server = request.makeServiceCall(ConstantsFileName.URL_CONTACT_UPLOAD, HttpRequest.POST , mContact.toListNameValuePair());
		return null;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		if(!ToolsSaveFile.checkStringNotNull(result_from_server)){
			return;
		}else{
			try{
				
				//**** Parse data to list contact
				JSONObject jsonObject = new JSONObject(result_from_server);
				int success = jsonObject.getInt(ConstantsFileName.success_field);
				if(success <= 0 ){
					return;
				}
				
				int id = jsonObject.getInt(ConstantsFileName.data_field);
				
				//**** Save List Contact
				mContact.setIsSync(1);
				mContact.set_Id(id);
				db.updateContact(mContact.getPrimaryKey(), mContact);
				
				//**** Post to broadcast
				Intent intent_finish = new Intent(ConstantsFileName.TAG_BROADCAST);
				intent_finish.putExtra(ConstantsFileName.TAG_FINISH_UPDATE , true);
		        context.sendBroadcast(intent_finish);
				
				
			}catch(Exception e){
				e.printStackTrace();
			}
			
		}
		
		try{
			if (db != null) {
				db.close();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	/**
	 * Check Login - (-1) : if not login. - id_login : if logged in.
	 */
	int checkLogin() {
		int id = -1;
		ToolsSaveFile tsf = new ToolsSaveFile();

		String id_loggedin = tsf.LoadContentFile(context,
				ConstantsFileName.FILE_ID_LOG_IN);

		if (id_loggedin == null || id_loggedin.equals("")
				|| id_loggedin.length() == 0) {

			id = -1;
		} else {
			try {
				id = Integer.parseInt(id_loggedin);

			} catch (Exception e) {
				id = -1;
				e.printStackTrace();
			}
		}

		return id;
	}
	
}
